<template>
  <!-- <view class="assessList getAssHeight" :style="{ marginBottom: padBottom }"> -->
  <view class="assessList" :style="{ minHeight: scrHeight + 'px' }">
    <!-- <view class="assessList getAssHeight"> -->
    <view v-for="(item, index) in curData" :key="index" :class="['talkBox', 'topRpx' + (index + 1)]">
      <view :class="['talkRow talkLeft', 'titleHeight' + (index + 1)]">
        <view class="talk">
          <img :src="require('../images/icons/whlogo.png')" />
          <view v-if="item.loading" class="loadingBox">
            <view class="pulse-container">
              <view class="pulse-bubble pulse-bubble-1"></view>
              <view class="pulse-bubble pulse-bubble-2"></view>
              <view class="pulse-bubble pulse-bubble-3"></view>
            </view>
          </view>
          <view v-else class="txt">
            {{ item.name }}
            <view v-if="item.unit" class="tips"
              ><img :src="require('./../images/icons/tipsIcon.png')" />请注意，数值单位是{{ item.unit }}哦!</view
            >
            <view v-if="item.tips" class="tips"
              ><img :src="require('./../images/icons/tipsIcon.png')" />{{ item.tips }}</view
            >
          </view>
        </view>
      </view>
      <!-- 单选框 -->
      <view v-if="item.type === 'radio' && !item.valueTxt && !item.loading" class="talkRow talkRight">
        <view class="talk">
          <view v-for="(optItem, optIndex) in item.option" :key="optIndex" class="txt">
            <span @click="radioChose(index, optItem)">{{ optItem.name }}</span>
          </view>
        </view>
        <view :class="['inputNumbersubmit', 'talkNow' + (index + 1)]">
          <span v-if="!item.rules.require" class="notKnow" @click="radioChose(index, optItem, 'refuse')">不知道</span>
        </view>
      </view>
      <!-- 多选框 -->
      <view v-if="item.type === 'checkbox' && item.valueTxt.length < 1 && !item.loading" class="talkRow talkRight">
        <view class="talk">
          <view v-for="(optItem, optIndex) in item.option" :key="optIndex" class="txt">
            <span
              :class="[item.value.some((itVal) => itVal === optItem.value) ? 'cur' : null]"
              @click="checkboxChose(index, optItem)"
              >{{ optItem.name }}</span
            >
          </view>
        </view>
        <view v-if="item.rulesTxt">{{ item.rulesTxt }}</view>
        <view :class="['inputNumbersubmit', 'talkNow' + (index + 1)]">
          <span v-if="!item.rules.require" class="notKnow" @click="checkBoxSubmit(index, item, 'refuse')">不知道</span>
          <span class="submitStyle" @click="checkBoxSubmit(index, item)">提交</span>
        </view>
      </view>
      <!-- 数字输入框 -->
      <view v-if="item.type === 'inputNumber' && !item.valueTxt && !item.loading" class="talkRow talkRight">
        <view class="talk">
          <view class="inputNumberStyle">
            <input
              id="height"
              v-model="item.value"
              type="digit"
              class="uni-input lineHeight86"
              name="height"
              placeholder-class="phcolor"
              @focus="clearTips(index)"
            />
          </view>
          <view v-if="item.rulesTxt">{{ item.rulesTxt }}</view>
          <view :class="['inputNumbersubmit', 'talkNow' + (index + 1)]">
            <span v-if="!item.rules.require" class="notKnow" @click="inputNumberSubmit(index, item, 'refuse')"
              >不知道</span
            >
            <span class="submitStyle" @click="inputNumberSubmit(index, item)">提交</span>
          </view>
        </view>
      </view>
      <view v-if="item.valueTxt && item.valueTxt.length > 0" class="talkRow talkRight answer">
        <view class="talk talkUser">
          <view class="headImg"><img :src="headImg" /></view>
          <view :class="['txt', 'noBorder', 'talkNowReg' + (index + 1)]">
            <span>{{ item.valueTxt | itemFilter }}</span>
          </view>
        </view>
      </view>
    </view>
    <!-- 结果 -->
    <view v-if="currentRisk" class="padding24">
      <view class="talkRow talkLeft">
        <view class="talk">
          <img :src="require('../images/icons/whlogo.png')" />
          <view v-if="item.loading" class="loadingBox">
            <view class="pulse-container">
              <view class="pulse-bubble pulse-bubble-1"></view>
              <view class="pulse-bubble pulse-bubble-2"></view>
              <view class="pulse-bubble pulse-bubble-3"></view>
            </view>
          </view>
          <view v-else class="txt">
            <view>根据您的答题结果您的评估结果为:</view>
            <view class="bigred" :style="{ color: currentRisk.color }">{{ currentRisk.text }}</view>
            <view>{{ currentRisk.remark }}</view>
          </view>
        </view>
        <view class="talk marginTop20">
          <img :src="require('../images/icons/whlogo.png')" />
          <view v-if="item.loading" class="loadingBox">
            <view class="pulse-container">
              <view class="pulse-bubble pulse-bubble-1"></view>
              <view class="pulse-bubble pulse-bubble-2"></view>
              <view class="pulse-bubble pulse-bubble-3"></view>
            </view>
          </view>
          <view v-else class="txt">
            <view>接下来您想做什么？</view>
          </view>
        </view>
      </view>
      <!-- 单选框 -->
      <view class="talkRow talkRight">
        <view class="talk">
          <view class="txt">
            <span @click="reloadPage">重新评估</span>
          </view>
          <view class="txt">
            <span @click="goServerPage">返回</span>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
/* eslint-disable no-invalid-this */
import { getInservice, getCcvdAssessment, getUserInfoByPatientId } from '@/api/cardiovascular';
import { addPhysicalExamination } from '@/api/assessQuestion';
import { debounce, getDataTime } from '@/utils/optimize';
import { mainData } from './cardiovascularData';
import { checkRules } from './checkData';
import { getAge } from '@/utils/optimize.js';
import { registerSource } from '@/common/baseUrl.js';
// 家人关系
export default {
  filters: {
    itemFilter: function (value) {
      if (Object.prototype.toString.call(value) === '[object Array]') {
        return value.join();
      }
      return value;
    }
  },
  props: {
    // 是否展示搜索按钮
    patientId: {
      type: String,
      default: ''
    },
    optionRelation: {
      type: Number,
      default: ''
    },
    optionSex: {
      type: Number,
      default: ''
    }
  },
  data() {
    return {
      scrollTop: 0,
      mainData: JSON.parse(JSON.stringify(mainData)),
      curTitleNumber: 0,
      curData: [],
      userInfo: null,
      currentRisk: null,
      riskList: {
        lowerRisk: {
          image: 'lower-risk',
          color: '#F48E18',
          text: '低危风险',
          remark: '应该接受生活方式指导，以保持自身的低风险状况，加强自我监测。'
        },
        middleRisk: {
          image: 'middle-risk',
          color: '#E95513',
          text: '中危风险',
          remark: '应积极改变不良生活方式，如戒烟、控制体重、增加体力活动等，如有必要可以在临床医生指导下进行相关治疗。'
        },
        highRisk: {
          image: 'high-risk',
          color: '#C8161D',
          text: '高危风险',
          remark:
            '应积极改变不良生活方式，如戒烟、控制体重、增加体力活动等，同时应该针对自身危险因素，在临床医生指导下进行降压、调脂、降糖等药物治疗。至少每年进行一次体检，必要时可以进行心脏超声、颈动脉超声等详细的影像学检查，以进一步评估心脑血管病风险。'
        }
      },
      screenHeight: 0,
      talkHeight: 0,
      padBottom: 0,
      man:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/man.png',
      woman:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/woman.png',
      son:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/son.png',
      father:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/father.png',
      der:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/der.png',
      mother:
        'https://wanhuhealth.oss-cn-beijing.aliyuncs.com/wanhuhealth-small-program/wanhu-mini-welfare/welfare/index/mother.png',
      headImg: '',
      scrHeight: '',
      scrHeightTop: '',
      regHeight: '',
      titleHeightNum: ''
    };
  },
  computed: {
    loginPatientId() {
      return wx.getStorageSync('patientid') || '';
    }
  },
  watch: {
    talkHeight(newVal, oldVal) {
      this.padBottom = this.screenHeight - (newVal - oldVal);
    }
  },
  mounted() {
    // this.patientId = '159560837ed245e284a155d4e0d66f09';
    this.getUserInfo();
    this.initCurDataObj();
    this.getAppAgent();
    this.headImg = this.headImgFilter();
    // this.getTalkHeight();
  },
  methods: {
    getAppAgent() {
      let self = this;
      // 获取系统信息
      wx.getSystemInfo({
        success: function (res) {
          // 获取可使用窗口宽度
          let clientHeight = res.windowHeight;
          // 获取可使用窗口高度
          // let clientWidth = res.windowWidth;
          // 算出比例
          // let ratio = 750 / clientWidth;
          // 算出高度(单位rpx)
          // let height = clientHeight * ratio;
          // 设置高度
          self.screenHeight = clientHeight;
        }
      });
    },
    // 更新最后一个对话框的高度
    getTalkHeight() {
      // 创建节点选择器
      // const query = wx.createSelectorQuery();
      const query = uni.createSelectorQuery().in(this);
      // 选择id
      const self = this;
      query
        .select('.talkNowReg' + self.curData.length)
        .boundingClientRect(function (rect) {
          self.talkHeight = rect.height;
          self.scrHeightTop = rect.top; // .screenHeight - rect.bottom;
          self.regHeight = rect.height;
        })
        .exec();
      query
        .select('.titleHeight' + self.curData.length)
        .boundingClientRect(function (rect) {
          self.titleHeightNum = rect.height;
        })
        .exec();
      setTimeout(function () {
        self.getTalkHeightNow();
      }, 0);
    },
    getTalkHeightNow() {
      // 创建节点选择器
      const query = wx.createSelectorQuery();
      // const query = uni.createSelectorQuery().in(this);
      // 选择id
      const self = this;
      query
        .select('.getAssHeight')
        .boundingClientRect(function (rect) {
          self.scrHeight =
            Number(self.scrHeightTop) + Number(rect.height) - Number(self.regHeight) - Number(self.titleHeightNum) - 40;
          self.debounceToPageScroll();
        })
        .exec();
      setTimeout(function () {
        self.next();
      }, 600);
    },
    // 单选提交
    radioChose(index, item, isRefuse) {
      if (isRefuse) {
        this.curData[index].value = '';
        this.curData[index].valueTxt = '不知道';
      } else {
        this.curData[index].value = item.value;
        this.curData[index].valueTxt = item.name;
      }
      const self = this;
      setTimeout(function () {
        self.getTalkHeight();
      }, 0);
    },
    // input输入提交
    inputNumberSubmit(index, item, isRefuse) {
      if (isRefuse) {
        this.curData[index].value = '';
        this.curData[index].valueTxt = '不知道';
      } else {
        this.curData[index].value = item.value;
        const check = this.checkData();
        if (!check) {
          this.$set(this.curData[index], 'rulesTxt', `数据异常，请重新录入`);
          return false;
        } else {
          this.$set(this.curData[index], 'rulesTxt', '');
        }
        this.curData[index].valueTxt = item.value;
      }
      const self = this;
      setTimeout(function () {
        self.getTalkHeight();
      }, 0);
    },
    // 多选提交
    checkBoxSubmit(index, item, isRefuse) {
      if (isRefuse) {
        this.curData[index].value = '';
        this.curData[index].valueTxt = '不知道';
      } else {
        const data = item.option.filter((optItem) => item.value.some((valItem) => valItem === optItem.value));
        let arr = [];
        data.forEach((mapItem) => {
          arr.push(mapItem.name);
        });
        const check = this.checkData();
        if (!check) {
          this.$set(this.curData[index], 'rulesTxt', `请选择选项`);
          return false;
        } else {
          this.$set(this.curData[index], 'rulesTxt', '');
        }
        this.curData[index].valueTxt = arr;
      }
      const self = this;
      setTimeout(function () {
        self.getTalkHeight();
      }, 0);
    },
    checkboxChose(index, item) {
      const haveIndex = this.curData[index].value.findIndex((findItem) => findItem === item.value);
      const conflictData = this.curData[index].option.find((curItem) => curItem.conflict);
      const curConflictIndex = this.curData[index].value.findIndex((curItem) => curItem === conflictData.value);
      if (haveIndex > -1) {
        this.curData[index].value.splice(haveIndex, 1);
        // this.curData[index].valueTxt.splice(haveIndex, 1);
      } else {
        this.curData[index].value.push(item.value);
        // this.curData[index].valueTxt.push(item.name);
      }
      if (curConflictIndex > -1) {
        this.curData[index].value.splice(curConflictIndex, 1);
        // this.curData[index].valueTxt.splice(curConflictIndex, 1);
      }
      if (curConflictIndex === -1 && item.conflict) {
        this.curData[index].value = [item.value];
        // this.curData[index].valueTxt = [item.name];
      }
    },
    initCurDataObj() {
      const self = this;
      this.curData.push(this.mainData[0]);
      this.$set(this.curData[0], 'loading', true);
      setTimeout(function () {
        self.$set(self.curData[0], 'loading', false);
      }, 500);
    },
    async getUserInfo() {
      const { data } = await getUserInfoByPatientId(this.patientId);
      this.userInfo = data;
    },
    debounceToPageScroll: debounce(function (e) {
      this.toPageBottom();
    }, 0),
    toPageBottom() {
      let that = this;
      wx.createSelectorQuery()
        .select('#scrollBox')
        .boundingClientRect(function (rect) {
          wx.pageScrollTo({
            scrollTop: rect.height,
            duration: 500 // 滑动速度
          });
          that.scrollTop = rect.height - that.scrollTop;
        })
        .exec();
    },
    toPageTop() {
      let that = this;
      wx.createSelectorQuery()
        .select('#scrollBox')
        .boundingClientRect(function (rect) {
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 1000 // 滑动速度
          });
          that.scrollTop = 0;
        })
        .exec();
    },
    checkData() {
      const index = this.curData.length === 0 ? 0 : this.curData.length - 1;
      let isPass = true;
      // 当前数据校验（必填、取值范围，保留小数位数等，rules都设置在cardiovascularData.js 的rules中）
      if (this.curData.length > 0 && this.curData[index].rules) {
        isPass = checkRules(this.curData[index]);
      }
      if (!isPass) {
        return false;
      }
      return isPass;
    },
    next() {
      // 展示下一题
      const self = this;
      if (this.curData.length < this.mainData.length) {
        this.curData.push(this.mainData[this.curData.length]);
        this.$set(this.curData[this.curData.length - 1], 'loading', true);
        setTimeout(function () {
          self.$set(self.curData[self.curData.length - 1], 'loading', false);
          // self.debounceToPageScroll();
        }, 500);
        // self.debounceToPageScroll();
      } else {
        // 没有更多题目了，在这里提交
        this.submitData();
        // uni.showToast({ title: '没有更多题目了', icon: 'none' });
      }
    },
    async submitData() {
      const self = this;
      // 处理性别和年龄
      const { sex, birthday } = this.userInfo;
      // 正常录入赋值
      let sendData = {};
      this.curData.forEach((item) => {
        sendData[item.key] = item.value;
        if (item.key === 'urbanRural' && !item.value && item.value !== 0) {
          sendData[item.key] = sex === 1 ? 1 : 0;
        }
        if (item.key === 'region' && !item.value && item.value !== 0) {
          sendData[item.key] = 1;
        }
        if (item.key === 'waistline' && !item.value && item.value !== 0) {
          sendData[item.key] = 80;
        }
        if (item.key === 'tc' && !item.value && item.value !== 0) {
          sendData[item.key] = 5.689;
        }
        if (item.key === 'hdlc' && !item.value && item.value !== 0) {
          sendData[item.key] = 2.069;
        }
      });
      // 获取服务包id
      const { data: serviceList } = await getInservice(this.patientId);
      const isService = serviceList.find((item) => {
        const pro = item.products.filter((pro) => pro.insuranceProductType === 3);
        return pro && pro.length > 0;
      });
      if (isService) {
        const { products } = isService;
        const pro = products.find((item) => item.insuranceProductType === 3);
        sendData.insuranceOrderProductId = pro.id;
      }
      // 处理性别和年龄
      sendData.gender = sex === 1 ? '男' : sex === 0 ? '女' : '';
      sendData.age = birthday ? getAge(birthday) : '';
      // 女性城市农村选项指定传农村
      sendData.urbanRural = sex === 1 ? 1 : 0;
      // 心脑血管老接口数据处理（吸烟、家属患病、单位转换）
      sendData.smoke = sendData.smoke <= 1 ? sendData.smoke : 1;
      sendData.ASCVDFamilyHistory = sendData.ASCVDFamilyHistory.some((item) => item === '0' || item === 0) ? 0 : 1;
      sendData.ASCVDFamilyHistory = sex === 1 ? sendData.ASCVDFamilyHistory : 0; // 如果为女性，直接传0
      sendData.tc = (sendData.tc * 38.67).toFixed(3);
      sendData.hdlc = (sendData.hdlc * 38.67).toFixed(3);
      const { data } = await getCcvdAssessment(this.patientId, sendData);
      const riskList = this.riskList;
      const { assessmentResult } = data;
      this.currentRisk = riskList.lowerRisk;
      if (assessmentResult * 100 >= 10.0) {
        this.currentRisk = riskList.highRisk;
      } else if (assessmentResult * 100 > 5.0 && assessmentResult * 100 < 10.0) {
        this.currentRisk = riskList.middleRisk;
      } else {
        this.currentRisk = riskList.lowerRisk;
      }

      setTimeout(function () {
        self.$set(self.curData[self.curData.length - 1], 'loading', false);
        self.debounceToPageScroll();
      }, 500);

      // self.debounceToPageScroll();
      // 提交健康档案
      this.subHealthFun(sendData);
    },
    async subHealthFun(filterData) {
      let sendData = {};
      this.curData.forEach((item) => {
        sendData[item.key] = item.value;
      });
      console.log(sendData);
      if (sendData.smoke === 0) {
        sendData.smoke = 10;
      } else if (sendData.smoke === 0.5) {
        sendData.smoke = 30;
      } else if (sendData.smoke === 2) {
        sendData.smoke = 20;
      } else {
        sendData.smoke = 40;
      }
      let data = {
        physicalExaminationDate: getDataTime(),
        createBy: this.loginPatientId,
        useDrug: sendData.isHypotensor,
        SBP: sendData.currentSBP,
        smok: sendData.smoke,
        waistline: sendData.waistline,
        TCHO: sendData.tc,
        HDL: sendData.hdlc,
        source: registerSource,
        businessSource: 1
      };
      // 个人慢病
      let ownIcd10Item = [{ icd10: sendData.diabetes === 1 ? 'E11' : undefined }];
      data.patientChronicDiseases = sendData.diabetes === 1 ? ownIcd10Item : [];
      // 亲属慢病
      let icd10Item = [];
      sendData.ASCVDFamilyHistory.forEach((item) => {
        let obj = {
          icd10: item,
          relation: 17
        };
        icd10Item.push(obj);
      });
      data.patientFamilyDiseases = icd10Item.some((item) => item.icd10 === '0') ? [] : icd10Item;
      // return false;
      await addPhysicalExamination(this.patientId, data);
    },
    clearTips(index) {
      this.curData[index].rulesTxt = '';
    },
    headImgFilter() {
      let src;
      if (this.optionSex === 1) {
        // 只有父母和子女需要区分性别
        if (this.optionRelation === 3) {
          src = this.father;
        } else if (this.optionRelation === 4) {
          src = this.son;
        } else {
          src = this.man;
        }
      } else {
        if (this.optionRelation === 3) {
          src = this.mother;
        } else if (this.optionRelation === 4) {
          src = this.der;
        } else {
          src = this.woman;
        }
      }
      // 如果是本人的话，则使用微信头像
      if (this.optionRelation === 1) {
        this.userInfo = JSON.parse(wx.getStorageSync('rawData'));
        src = this.userInfo.avatarUrl || this.man;
      }
      return src;
    },
    goServerPage() {
      uni.reLaunch({
        // url: '/pages/service/index?patientId=' + this.patientId
        url: '/pages/index/index?patientId=' + this.patientId
      });
    },
    reloadPage() {
      // this.curData = [];
      // this.currentRisk = null;
      // this.getUserInfo();
      // this.initCurDataObj();
      // this.toPageTop();
      uni.redirectTo({
        url: '/pagesB/cardiovascularAssess/assessList?patientId=' + this.patientId
      });
    }
  }
};
</script>

<style lang="scss">
@import './../style/assessList.scss';
</style>
<style>
/* KEYFRAMES */

@keyframes spin {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(359deg);
  }
}

@keyframes configure-clockwise {
  0% {
    transform: rotate(0);
  }
  25% {
    transform: rotate(90deg);
  }
  50% {
    transform: rotate(180deg);
  }
  75% {
    transform: rotate(270deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes configure-xclockwise {
  0% {
    transform: rotate(45deg);
  }
  25% {
    transform: rotate(-45deg);
  }
  50% {
    transform: rotate(-135deg);
  }
  75% {
    transform: rotate(-225deg);
  }
  100% {
    transform: rotate(-315deg);
  }
}

@keyframes pulse {
  from {
    opacity: 1;
    transform: scale(1);
  }
  to {
    opacity: 0.25;
    transform: scale(0.75);
  }
}
</style>
